<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>智能推荐</title>
    <link rel="stylesheet" href="../../static/layui/css/layui.css">
    <script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://cdn.staticfile.org/popper.js/1.12.5/umd/popper.min.js"></script>
    <script type="text/javascript"
            src="https://cdn.staticfile.org/twitter-bootstrap/4.1.0/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="../../static/markdown/marked.min.js"></script>
    <style>
        body {
            background-color: #f1f1f1;
        }
        .alert {
            position: relative;
            padding: .75rem 1.25rem;
            margin-bottom: 1rem;
            border: 1px solid transparent;
            border-radius: .25rem
        }

        .close {
            position: absolute;
            top: 0;
            right: 0;
            padding: .75rem 1.25rem;
            color: inherit
        }

        .alert-warning {
            color: #856404;
            background-color: #fff3cd;
            border-color: #ffeeba
        }

        .close {
            float: right;
            font-size: 1.5rem;
            font-weight: 700;
            line-height: 1;
            color: #000;
            text-shadow: 0 1px 0 #fff;
            opacity: .5
        }

        .close:focus, .close:hover {
            color: #000;
            text-decoration: none;
            opacity: .75
        }

        .close:not(:disabled):not(.disabled) {
            cursor: pointer
        }

        button.close {
            padding: 0;
            background-color: transparent;
            border: 0;
            -webkit-appearance: none
        }

        .close {
            padding: 1rem;
            margin: -1rem -1rem -1rem auto
        }

        .alert-dismissible .close {
            position: absolute;
            top: 0;
            right: 0;
            padding: .75rem 1.25rem;
            color: inherit
        }

        .height-light {
            span {
                background-color: #009688;
            }
        }

        .layui-layout-admin .layui-logo {
            font-size: 24px;
            transition: all 0.5s;
        }

        .layui-layout-admin .layui-logo:hover {
            font-size: 40px;

            img {
                width: 30px;
            }
        }

        .layui-layout-admin .layui-logo img {
            width: 15px;
            margin-left: 5px;
            margin-top: 10px;
            transition: all 0.5s;
        }

        .layui-layout-admin .layui-body {
            top: 120px;
            right: 200px;
        }

        .layui-layout-admin .layui-footer {
            left: 0;
            right: 0;
            text-align: center;
        }

        .tab-bar {
            margin: 0 auto;
            width: calc(100% - 520px);
            height: 40px;
            background-color: rgb(35, 38, 46);
            display: flex;
            justify-content: space-around;
            border-radius: 0 0 40px 40px;
        }

        .tab-bar .tab-bar-item {
            a {
                color: #ffffff;
                display: block;
            }
            span {
                height: 5px;
                display: block;
            }
            align-self: center;
            height: 40px;
        }

        .tab-bar .tab-bar-item:hover {
            span {
                background-color: #009688;
            }
        }

        #li_4:hover {
            .tab-bar-item-item-parent {
                display: block;
            }
            .tab-bar-item-item {
                display: block;
            }
        }

        .tab-bar-item-item-parent {
            display: none;
            background-color: rgb(35, 38, 46);
            position: absolute;
            top: 60px;
            padding: 0 10px 5px 10px;
            border-radius: 5px;
        }
        .tab-bar-item-item-parent:hover {
            display: block;
            .tab-bar-item-item {
                display: block;
            }
        }
        .tab-bar-item-item {
            display: none;
            margin-top: 5px;
        }
        .tab-bar-item-item:hover {
            display: block;
            a {
                color: #25bba4;
            }
        }

        .title {
            position: fixed;
            top: 130px;
            left: 230px;
        }

        .container {
            position: fixed;
            bottom: 110px;
            left: 280px;
            right: 400px;
            width: calc(100% - 620px);
            height: 10px;
            margin: 0;
            padding: 10px;
            background-color: #f1f1f1;
            border-radius: 5px;
            overflow-y: scroll;
        }

        .container > * {
            margin-bottom: 10px; /* 设置元素之间的外边距 */
            font-size: 16px;
        }

        /* 最后一个元素不设置右侧外边距 */
        .container > *:last-child {
            margin-bottom: 0;
        }

        .input {
            position: fixed;
            bottom: 44px;
            right: 120px;
            width: calc(100% - 220px);
            padding: 10px;
            text-align: center;
        }

        .input #textInput {
            height: 40px;
            width: calc(100% - 420px);
            border-radius: 10px;
            font-size: 16px;
            text-indent: 1ch;
        }

        .input #summit {
            height: 40px;
            width: 40px;
            border-radius: 50%;
            font-size: 14px;
            cursor: pointer;
        }

        .input #summit:hover {
            opacity: 0.8;
        }

        .img {
            height: 30px;
            width: 30px;
            margin-right: 5px;
            padding: 3px;
            border-radius: 50%;
            background-color: #c0effd;
            border: 1px solid #c0effd;
        }

        code {
            border-radius: 10px;
            margin: 5px 15px;
        }

        .div-answer {
            display: flex;
            flex-direction: column;
            gap: 10px; /* 上下间隔 */
        }

        #left-cover {
            position: fixed;
            height: 100%;
            width: 250px;
            top: -50px;
            left: -30px;
            background-color: #ffffff;
            border-radius: 30px;
        }

        #right-cover {
            position: fixed;
            height: 100%;
            width: 250px;
            top: -50px;
            right: -30px;
            background-color: #ffffff;
            border-radius:30px
        }
    </style>
</head>
<body class="layui-layout-body">
<div class="layui-layout layui-layout-admin">
    <div class="layui-header">
        <a href="{{ url_for('index_student') }}">
            <div class="layui-logo">图书<img src="../static/logo.png"></div>
        </a>
        <!-- 头部区域（可配合layui已有的水平导航） -->
        <ul class="layui-nav layui-layout-right">
            <li class="layui-nav-item">
                <a href="javascript:;">
                    <img src="../../static/avatar/{{avatar}}.png" class="layui-nav-img">
                    {{ name }}
                </a>
                <dl class="layui-nav-child">
                    <dd><a href="{{ url_for('user_info_student', id=current_user.card_id) }}">个人信息</a></dd>
                    <dd><a href="{{ url_for('change_password_student') }}">修改密码</a></dd>
                </dl>
            </li>
            <li class="layui-nav-item"><a href="{{ url_for('logout') }}">退出登录</a></li>
        </ul>
    </div>

    <div class="tab-bar">
        <div id="li_1" class="tab-bar-item">
            <a href="{{url_for('index_student')}}">首页</a>
            <span></span>
        </div>
        <div id="li_2" class="tab-bar-item">
            <a href="{{ url_for('recommend') }}">智能推荐</a>
            <span></span>
        </div>
        <div id="li_3" class="tab-bar-item">
            <a href="{{ url_for('search_book_student') }}">图书查询</a>
            <span></span>
        </div>
        <div id="li_4" class="tab-bar-item">
            <a href="javascript:;">图书管理▼</a>
            <div class="tab-bar-item-item-parent">
                <div class="tab-bar-item-item" id="li_4_1"><a href="{{ url_for('borrow_student') }}">图书借阅</a>
                </div>
                <div class="tab-bar-item-item" id="li_4_2"><a href="{{ url_for('return_book_student') }}">图书归还</a>
                </div>
            </div>
            <span></span>
        </div>
        <div id="li_5" class="tab-bar-item">
            <a href="{{ url_for('change_info_student') }}">信息设置</a>
            <span></span>
        </div>
        <div id="li_6" class="tab-bar-item">
            <a href="{{ url_for('announcement_student') }}">查看公告</a>
            <span></span>
        </div>
        <div id="li_7" class="tab-bar-item">
            <a href="{{ url_for('comments_student') }}">读者留言</a>
            <span></span>
        </div>
    </div>

    <div class="title">
        <h2>智能推荐</h2>
    </div>

    <div class="container" id="container">
        <div id="div-answer" class="div-answer">
            <div id="answer"></div>
        </div>
    </div>
    <div class="input">
        <input type="textarea" id="textInput" placeholder="您有什么问题">
        <img onclick="run_prompt()" id="summit" src="../../static/summit.png"/>
    </div>

    <div class="layui-footer">
        Copyright 2024 Construct
    </div>

    <div id="left-cover"></div>
    <div id="right-cover"></div>
</div>
<link rel="stylesheet" href="../../static/highlight/styles/atom-one-dark.css">
<script src="../../static/highlight/highlight.js"></script>
<script>hljs.highlightAll();</script>
<script type="text/javascript" src="../../static/layui/layui.js"></script>
<script>
    layui.use('element', function () {
        var element = layui.element;
        element.init();
    });

    $(document).ready(function () {
        $("#li_2").addClass("height-light");
        $("#container").css({
            'position': 'fixed',
            'bottom': '110px',
            'left': '280px',
            'width': 'calc(100% -500px)',
            'height': ($(window).height() - 350).toString() + "px",
            'margin': '0',
            'padding': '10px',
            'background-color': '#f1f1f1f1',
            'border-radius': '10px',
        });
        var inputElement = document.getElementById('textInput');

        inputElement.addEventListener('keydown', function (event) {
            if (event.key === "Enter" && inputElement.value !== "" && inputElement.value !== null) {
                run_prompt();
            }
        });

        var scrollContainer = document.getElementById('container');
        var isUserScrolling = false;
        var lastScrollTop = 0;

        function scrollToBottom() {
            scrollContainer.scrollTop = scrollContainer.scrollHeight;
        }

        function handleScroll() {
            var scrollTop = scrollContainer.scrollTop;
            var scrollHeight = scrollContainer.scrollHeight;
            var clientHeight = scrollContainer.clientHeight;

            if ((scrollTop + clientHeight) >= (scrollHeight - 300)) {
                scrollToBottom();
            }
        }

        // 使用setInterval设置调用间隔时间
        setInterval(handleScroll, 200);
    });

    current_text = document.getElementById('answer');
    var text = "";
    var markdown = "";
    var char_index = 0;
    var counter = 0;
    var msg = [];


    async function run_prompt() {
        var input = document.getElementById('textInput');
        var img = document.getElementById('summit');
        var inputValue = input.value;
        if (text === "") {
            msg.push({"role": "user", "content": inputValue});
        } else {
            msg.push({"role": "assistant", "content": text});
            msg.push({"role": "user", "content": inputValue});
        }
        addNewAnswerParagraph();
        document.getElementById('answer').value = "";
        // 清空输入框
        input.value = "";
        // 设置回答状态输入框不可用
        input.disabled = true;
        // 设置发送按钮变为终止按钮
        img.src = "../../static/generate.png";

        async function extracted() {
            fetch('http://localhost:5000/eb_stream', {
                method: 'post',
                headers: {'Content-Type': 'text/plain'},
                body: JSON.stringify({"msg": msg})
            }).then(response => {
                text = "";
                markdown = "";
                char_index = 0;
                return response.body;
            }).then(body => {
                const reader = body.getReader();
                const decoder = new TextDecoder();

                function read() {
                    return reader.read().then(({done, value}) => {
                        if (done) { // 读取完成
                            // 设置回答状态输入框可用
                            input.disabled = false;
                            // 设置发送按钮变为终止按钮
                            img.src = "../../static/summit.png";
                            return;
                        }
                        data = decoder.decode(value, {stream: true});
                        // console.log(data);
                        // data = data.replace(/�/g, '');
                        console.log(data);
                        text += JSON.parse(data).result;
                        type();  // 打字机效果输出
                        return read();
                    });
                }

                hljs.highlightAll();
                return read();
            }).catch(error => {
                console.error('发生错误:', error);
            });
        }

        // 调用服务端的流式接口, 修改为自己的服务器地址和端口号
        await extracted();
    }

    function type() {
        /**
         let enableCursor = true;  // 启用光标效果
         if (char_index < text.length) {
         let txt = document.getElementById('answer').value;
         let cursor = enableCursor ? "|" : "";
         if (enableCursor && txt.endsWith("|")) {
         txt = txt.slice(0, -1);
         }
         document.getElementById('answer').value = txt + text.charAt(char_index) + cursor;
         char_index++;
         setTimeout(type, 1000/10);  // 打字机速度控制, 每秒5个字
         } **/

        let enableCursor = true;  // 启用光标效果
        let cursor = "";
        if (char_index < text.length) {
            markdown = markdown + text.charAt(char_index);
            let html = marked.parse(markdown);
            let pElement = document.getElementById('answer');
            pElement.innerHTML = html;
            char_index++;
            setTimeout(type, 1000 / 20);  // 打字机速度控制
        }
        if (cursor === "|") {
            // 最后删除光标
        }
        hljs.highlightAll();
    }

    function addNewAnswerParagraph() {
        let inputValue = document.getElementById('textInput').value;
        // 改原来的id
        let paragraphDiv = document.getElementById("div-answer");
        let paragraph = document.getElementById("answer");
        try {
            paragraph.removeChild(paragraph.lastChild);
        } catch (e) {
        }
        paragraphDiv.id = "div-answer" + counter;
        paragraph.id = "answer" + counter;
        // 创建一个新的图片元素
        let img = document.createElement('img');
        // 设置图片的 URL
        img.src = "../../static/user_icon.png"; // 这里替换为您的图片 URL
        img.className = "img";
        let container = document.getElementById("container");
        // 创建一个新的 <div> 元素
        let promptParagraphDiv = document.createElement("div");
        let promptParagraph = document.createElement("div");
        promptParagraph.style.backgroundColor = "#f1f1f1";
        promptParagraph.style.borderRadius = "10px";
        promptParagraph.style.padding = "10px 30px";
        promptParagraphDiv.appendChild(img.cloneNode(true));
        promptParagraphDiv.appendChild(promptParagraph);
        // promptParagraph.appendChild(img.cloneNode(true));
        // 设置新元素的 id
        promptParagraphDiv.id = "div-prompt" + counter;
        promptParagraph.id = "prompt" + counter;
        // 创建包含文本的文本节点
        let textNode1 = document.createTextNode(inputValue);
        // 将文本节点添加到段落中
        promptParagraph.appendChild(textNode1);
        // 将新的 <p> 元素添加到容器中
        container.appendChild(promptParagraphDiv);

        // 创建一个新的 <div> 元素
        let newParagraphDiv = document.createElement("div");
        let newParagraph = document.createElement("div");
        // 设置新元素的 id
        newParagraphDiv.id = "div-answer";
        newParagraph.id = "answer";
        newParagraph.className = "div-answer";
        newParagraph.style.backgroundColor = "#FFFFFF";
        newParagraph.style.borderRadius = "10px";
        newParagraph.style.padding = "20px";
        newParagraph.style.marginTop = "10px";
        // 将新的 <p> 元素添加到容器中
        newParagraphDiv.appendChild(newParagraph);
        container.appendChild(newParagraphDiv);
        addImg();
        // 更新计数器
        counter++;
    }

    function addImg() {
        let img = document.createElement('img');
        // 设置图片的 URL
        img.src = "../../static/bot.png"; // 这里替换为您的图片 URL
        img.className = "img";
        let paragraph = document.getElementById("div-answer");
        // 获取段落的第一个子节点（文本节点）
        let textNode = paragraph.firstChild;
        // 在文本节点前面插入图片
        paragraph.insertBefore(img.cloneNode(true), textNode);
    }
</script>
</body>
</html>
